<?php

// +----------------------------------------------------------------------
// | Fanwe 方维众筹商业系统
// +----------------------------------------------------------------------
// | Copyright (c) 2011 http://www.fanwe.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 甘味人生(526130@qq.com)
// +----------------------------------------------------------------------

class XiacaiAction extends CommonAction {

    public function __construct() {
        parent::__construct();
        require_once APP_ROOT_PATH . "/admin/Lib/Action/VideoCommonAction.class.php";
    }

    /**
     * 瞎猜列表
     */
    public function index() {
        if (strim($_REQUEST['nick_name']) != '') {
            //name
            $user = M("User")->where("nick_name like '%" . trim($_REQUEST['nick_name']) . "%' ")->findAll();
            foreach ($user as $k => $v) {
                $user_arr_id[$k] = intval($v['id']);
            }
            $parameter .= "user_id in (" . implode(",", $user_arr_id) . ")&";
            $sql_w .= " and user_id in (" . implode(",", $user_arr_id) . ")";
        } else if (intval($_REQUEST['user_id']) > 0) {
            $parameter .= "user_id=" . intval($_REQUEST['user_id']) . "&";
            $sql_w .= " and user_id=" . intval($_REQUEST['user_id']);
        }
        $model = D();

        $sql_str = "select id, subject, start_time_tip, subscribe_count, user_id, room_id, sort, create_time from " . DB_PREFIX . "xiacai where 1=1";
        $count_sql = "SELECT count(*)  as tpcount FROM " . DB_PREFIX . "xiacai WHERE 1=1 ";

        $sql_str .= $sql_w;
        $count_sql .= $sql_w;
        $voList = $this->_Sql_list($model, $sql_str, "&" . $parameter, 'id', 0, $count_sql);
        $this->assign('url_name', get_manage_url_name());

        $this->assign('list', $voList);
        $this->display();
    }

    //推流地址
    public function push_url() {
        $video_id = intval($_REQUEST['id']);
        $push_url_info = $GLOBALS['db']->getRow("SELECT id,push_rtmp,play_flv,play_rtmp,play_mp4,play_hls FROM " . DB_PREFIX . "video WHERE id=" . $video_id, true, true);
        $this->assign("push_url", $push_url_info);
        $this->display();
    }

    // 瞎猜新增表单界面
    public function add() {
        $this->assign("sort", M("Xiacai")->max("sort") + 1);
        $this->display();
    }

    // 瞎猜编辑表单界面
    public function edit() {
        $id = intval($_REQUEST ['id']);
        $condition['id'] = $id;
        $vo = M('Xiacai')->where($condition)->find();
        $airtime = M('xiacai_airtime')->where(array('xiacai_id' => $id))->field('weekday,is_daily,start_time,time_xiacai')->select();
        $this->assign('vo', $vo);
        //exit(json_encode($airtime));
        $this->assign('airtime', json_encode($airtime));
        $this->assign('airtime_sign', md5(json_encode($airtime))); // 生成数据签名，这样如果编辑的时候数据没有更新，就不用改动附表了
        $this->display();
    }

    // 瞎猜新增写入数据库
    public function insert() {
        B('FilterString');
        $ajax = intval($_REQUEST['ajax']);
        $data = M('Xiacai')->create();
        // 开播时间
        $star_cycle = $_REQUEST['start_cycle']; // 开播周期
        $airtime = array(); // 开播时间表数据
        $atime_xiacai = array();
        if (empty($star_cycle) || trim($star_cycle) == '') {
            $this->error("请选择开播周期");
        } else {
            switch ($star_cycle) {
                case "week":
                    $weekday = $_REQUEST['weekday'];
                    foreach ($weekday as $wday) {
                        $start_time = $_REQUEST['start_time' . $wday];
                        if (empty($start_time) || strpos($start_time, ':') < 0) {
                            $this->error('请填写开播时间');
                        }
                        //$time_xiacai = ($wday == 0 ? 7 : $wday) . date('Hi', strtotime($start_time));
                        //$atime_xiacai[] = $time_xiacai;
                        $airtime[] = array('weekday' => $wday, 'start_time' => $start_time);
                    }
                    break;
                case "day":
                    $start_time = $_REQUEST['start_time'];
                    if (empty($start_time) || strpos($start_time, ':') < 0) {
                        $this->error('请填写开播时间');
                    }
                    //$time_xiacai = '9' . date('Hi', strtotime($start_time));
                    //$atime_xiacai[] = $time_xiacai;
                    // time_xiacai:开播具体日期和时间,例如 11500表示每周一15:00,71200表示每周日12:00,91200表示每天12:00(1-7表示周一到周日,9表示每天)
                    $airtime[] = array('is_daily' => 1, 'start_time' => $start_time);
                    break;
            }
        }
        //开始验证有效性
        $this->assign("jumpUrl", u(MODULE_NAME . "/add"));
        if (!check_empty($data['subject'])) {
            $this->error("请输入节目名称");
        }
        if (!check_empty($data['desc'])) {
            $this->error("请输入节目简介");
        }
        if (!check_empty($data['start_time_tip'])) {
            $this->error("请输入开播时间提示");
        }
        if (!check_empty($data['host_user_ids'])) {
            $this->error("请输入主持人");
        }
        if (!check_empty($data['user_id'])) {
            $this->error("请输入主播ID");
        }
        // 判断用户是否存在,多个用户之间去空项,去重复
        $user_id = $_REQUEST['user_id'];
        if (M('user')->where(array('id' => $user_id))->count() < 1) {
            $this->error('主播 ' . $user_id . ' 不存在');
        }
        $existsSubject = M('Xiacai')->where(array('user_id' => $user_id))->getField('subject');
        if ($existsSubject) {
            $this->error('一个主播只能有一个节目, 主播 ' . $user_id . ', 已经拥有节目[' . $existsSubject . ']');
        }
        $user_ids = $_REQUEST['host_user_ids'];
        $auser_ids = array_unique(array_filter(explode(' ', $user_ids))); // 去空项,去重复
        $existsUsers = M('user')->where(array('id' => array('in', $auser_ids)))->getField('id', true);
        $diffUsers = array_diff($auser_ids, $existsUsers);
        if (count($diffUsers) > 0) {
            $this->error('主持人ID ' . implode(',', $diffUsers) . ' 不存在');
        }
        $data['create_time'] = NOW_TIME;
        $data['host_user_ids'] = implode(' ', $auser_ids); // 去空项,去重复
        //$data['start_times'] = implode(',', $atime_xiacai); // 更新数据
        $log_info = $data['name'];
        $id = M('Xiacai')->add($data);
        if (false !== $id) {
            // 添加开播时间
            foreach ($airtime as $airtimedata) {
                $airtimedata['xiacai_id'] = $id;
                M('xiacai_airtime')->add($airtimedata);
            }
            // 添加主播列表
            foreach ($podcast_users as $podcast_user) {
                $podcast_user['xiacai_id'] = $id;
                M('xiacai_podcast')->add($podcast_user);
            }
            // 添加到redis
            fanwe_require(APP_ROOT_PATH . 'mapi/lib/redis/BaseRedisService.php');
            fanwe_require(APP_ROOT_PATH . 'mapi/lib/redis/XiacaiRedisService.php');
            $xiacai_redis = new XiacaiRedisService();
            $redis_data = M('Xiacai')->find($id);
            $xiacai_redis->insert_db($id, $redis_data);
            //成功提示
            save_log($log_info . L("INSERT_SUCCESS"), 1);
            $this->success(L("INSERT_SUCCESS"));
        } else {
            //错误提示
            save_log($log_info . L("INSERT_FAILED"), 0);
            $this->error(L("INSERT_FAILED"));
        }
    }

    // 瞎猜更新保存数据库
    public function update() {
        B('FilterString');
        $data = M('Xiacai')->create();
        $xiacai_id = intval($data['id']);
        // 开播时间
        $star_cycle = $_REQUEST['start_cycle']; // 开播周期
        $airtime = array(); // 开播时间表数据
        $atime_xiacai = array();
        if (empty($star_cycle)) {
            $this->error("请选择开播周期");
        } else {
            switch ($star_cycle) {
                case "week":
                    $weekday = $_REQUEST['weekday'];
                    foreach ($weekday as $wday) {
                        $start_time = $_REQUEST['start_time' . $wday];
                        if (empty($start_time) || strpos($start_time, ':') < 0) {
                            $this->error('请填写开播时间');
                        }
                        //$time_xiacai = ($wday == 0 ? 7 : $wday) . date('Hi', strtotime($start_time));
                        //$atime_xiacai[] = $time_xiacai;
                        $airtime[] = array('weekday' => $wday, 'is_daily' => '0', 'start_time' => $start_time);
                    }
                    break;
                case "day":
                    $start_time = $_REQUEST['start_time'];
                    if (empty($start_time) || strpos($start_time, ':') < 0) {
                        $this->error('请填写开播时间');
                    }
                    //$time_xiacai = '9' . date('Hi', strtotime($start_time));
                    //$atime_xiacai[] = $time_xiacai;
                    $airtime[] = array('weekday' => '0', 'is_daily' => '1', 'start_time' => $start_time);
                    break;
            }
        }
        //exit(json_encode($airtime));
        $airtime_sign = $_REQUEST['airtime_sign']; // 获取原来的数据签名
        $airtime_sign_cur = md5(json_encode($airtime)); // 生成当前数据签名
        //echo $airtime_sign, '<br />', $airtime_sign_cur, '<br />';
        $log_info = M('Xiacai')->where("id=" . $xiacai_id)->getField("subject");
        //开始验证有效性
        $this->assign("jumpUrl", u(MODULE_NAME . "/edit", array("id" => $xiacai_id)));
        if (!check_empty($data['subject'])) {
            $this->error("请输入节目名称");
        }
        if (!check_empty($data['desc'])) {
            $this->error("请输入节目简介");
        }
        if (!check_empty($data['start_time_tip'])) {
            $this->error("请输入开播时间提示");
        }
        if (!check_empty($data['host_user_ids'])) {
            $this->error("请输入主持人");
        }
        if (!check_empty($data['user_id'])) {
            $this->error("请输入主播ID");
        }
        // 判断用户是否存在,多个用户之间去空项,去重复
        $user_id = $_REQUEST['user_id'];
        if (M('user')->where(array('id' => $user_id))->count() < 1) {
            $this->error('主播 ' . $user_id . ' 不存在');
        }
        $existsSubject = M('Xiacai')->where(array('user_id' => $user_id))->getField('subject');
        if ($existsSubject) {
            $this->error('一个主播只能有一个节目, 主播 ' . $user_id . ', 已经拥有节目[' . $existsSubject . ']');
        }
        $user_ids = $_REQUEST['host_user_ids'];
        $auser_ids = array_unique(array_filter(explode(' ', $user_ids))); // 去空项,去重复
        $existsUsers = M('user')->where(array('id' => array('in', $auser_ids)))->getField('id', true);
        $diffUsers = array_diff($auser_ids, $existsUsers);
        if (count($diffUsers) > 0) {
            $this->error('主持人ID ' . implode(',', $diffUsers) . ' 不存在');
        }

        $data['host_user_ids'] = implode(' ', $auser_ids); // 去空项,去重复
        $data['is_update'] = 1; // 记录更新标识,用于推送客户端更新主持人
        //$data['start_times'] = implode(',', $atime_xiacai); // 更新数据
        // 更新数据
        $list = M('Xiacai')->save($data);
        if (false !== $list) {
            if ($airtime_sign != $airtime_sign_cur) { // 如果开播时间有更改，则更新到数据库
                // 删除开播时间
                M('xiacai_airtime')->where(array('xiacai_id' => $xiacai_id))->delete();
                // 添加开播时间
                foreach ($airtime as $airtimedata) {
                    $airtimedata['xiacai_id'] = $xiacai_id;
                    M('xiacai_airtime')->add($airtimedata);
                }
            }
            // 更新到redis
            fanwe_require(APP_ROOT_PATH . 'mapi/lib/redis/BaseRedisService.php');
            fanwe_require(APP_ROOT_PATH . 'mapi/lib/redis/XiacaiRedisService.php');
            $xiacai_redis = new XiacaiRedisService();
            $xiacai_redis->update_db($data['id'], $data);
            // 发送腾讯通知
            curl_http_get(get_domain() . '/mapi/index.php?ctl=guessing&act=notify_update&xiacai_id=' . $xiacai_id);
            //成功提示
            save_log($log_info . L("UPDATE_SUCCESS"), 1);
            $this->success(L("UPDATE_SUCCESS"));
        } else {
            //错误提示
            save_log($log_info . L("UPDATE_FAILED"), 0);
            $this->error(L("UPDATE_FAILED"), 0, $log_info . L("UPDATE_FAILED"));
        }
    }

    // 删除瞎猜节目
    public function foreverdelete() {
        //彻底删除指定记录
        $ajax = intval($_REQUEST['ajax']);
        $id = $_REQUEST ['id'];
        $id_array = array();
        if (isset($id)) {
            $id_array = explode(',', $id);
            $condition = array('id' => array('in', $id_array));
            $list = M(MODULE_NAME)->where($condition)->delete();
            if ($list !== false) {
                //redis同步
                fanwe_require(APP_ROOT_PATH . 'mapi/lib/redis/BaseRedisService.php');
                fanwe_require(APP_ROOT_PATH . 'mapi/lib/redis/XiacaiRedisService.php');
                $xiacai_redis = new XiacaiRedisService();
                foreach ($id_array as $id_str) {
                    $xiacai_redis->del_db(intval($id_str));
                }
                // 删除开播时间
                $GLOBALS['db']->query("delete from fanwe_xiacai_airtime where xiacai_id in ($id)");

                save_log($info . l("FOREVER_DELETE_SUCCESS"), 1);
                $this->success(l("FOREVER_DELETE_SUCCESS"), $ajax);
            } else {
                save_log($info . l("FOREVER_DELETE_FAILED"), 0);
                $this->error(l("FOREVER_DELETE_FAILED"), $ajax);
            }
        } else {
            $this->error(l("INVALID_OPERATION"), $ajax);
        }
    }

    public function start() {
        $xiacai_id = $_REQUEST['xiacai_id'];
        $xiacai = M('Xiacai')->find($xiacai_id);
        $this->assign("xiacai", $xiacai);
        $this->display();
    }

    //查看直播（web2.1播放器）
    public function play() {
        $video_id = $_REQUEST['video_id'];
        $xiacai_id = $_REQUEST['xiacai_id'];
        $condition['id'] = $video_id;
        $video = M('Video')->where($condition)->find();
        $m_config = load_auto_cache("m_config"); //初始化手机端配置
        $app_id = $m_config['vodset_app_id'];
        $this->assign('app_id', $app_id);
        if ($video['live_in'] != 1 && $video['play_url'] == '') {
            require_once APP_ROOT_PATH . "/mapi/lib/core/common.php";
            fanwe_require(APP_ROOT_PATH . 'mapi/lib/redis/BaseRedisService.php');
            $root = get_vodset_by_video_id($video_id);
            if (isset($root['vodset'])) {
                $play_list = array();
                $vodset = $root['vodset'];
                foreach ($vodset as $k => $v) {
                    $playSet = $v['fileSet'];
                    for ($i = sizeof($playSet) - 1; $i >= 0; $i--) {
                        $play_list[] = $playSet[$i]['fileId'];
                        $play_url_list[] = $playSet[$i]['playSet'];
                    }
                }
                foreach ($play_url_list as $k2 => $v2) {
                    foreach ($v2 as $kk => $vv) {
                        //mp4
                        if ($vv['definition'] == 0 && strpos($vv['url'], '.mp4')) {//原画mp4 播放URL
                            $video['mp4_url'] = $vv['url'];
                        }
                        if ($vv['definition'] == 10) {//手机mp4 播放URL
                            $video['mp4_sj_url'] = $vv['url'];
                        }
                        if ($vv['definition'] == 20) {//标清mp4 播放URL
                            $video['mp4_sd_url'] = $vv['url'];
                        }
                        if ($vv['definition'] == 40 || $vv['definition'] == 30) {//高清mp4 播放URL
                            $video['mp4_hd_url'] = $vv['url'];
                        }
                        //m3u8
                        if ($vv['definition'] == 0 && strpos($vv['url'], '.m3u8')) {//原画m3u8 播放URL
                            $video['m3u8_url'] = $vv['url'];
                        }
                        if (($vv['definition'] == 210) && strpos($vv['url'], '.m3u8')) {//手机m3u8 播放URL
                            $video['m3u8_url'] = $vv['url'];
                        }
                        if (($vv['definition'] == 220) && strpos($vv['url'], '.m3u8')) {//标清m3u8 播放URL
                            $video['m3u8_sd_url'] = $vv['url'];
                        }
                        if (($vv['definition'] == 230) && strpos($vv['url'], '.m3u8')) {//高清m3u8 播放URL
                            $video['m3u8_hd_url'] = $vv['url'];
                        }
                        //flv
                        if (strpos($vv['url'], '.flv') && $vv['definition'] == 0) {//原画flv 播放URL
                            $video['flv_url'] = $vv['url'];
                        }
                        if (strpos($vv['url'], '.flv') && $vv['definition'] == 0) {//手机flv 播放URL
                            $video['flv_sj_url'] = $vv['url'];
                        }
                        if (strpos($vv['url'], '.flv') && $vv['definition'] == 0) {//标清flv 播放URL
                            $video['flv_sd_url'] = $vv['url'];
                        }
                        if (strpos($vv['url'], '.flv') && $vv['definition'] == 0) {//高清flv 播放URL
                            $video['flv_hd_url'] = $vv['url'];
                        }
                        //rtmp
                        if (!strpos($vv['url'], '.flv') && !strpos($vv['url'], '.mp4') && !strpos($vv['url'], '.m3u8') && $vv['definition'] == 0) {//原画rtmp 播放URL
                            $video['rtmp_url'] = $vv['url'];
                        }
                        if (!strpos($vv['url'], '.flv') && !strpos($vv['url'], '.mp4') && !strpos($vv['url'], '.m3u8') && $vv['definition'] == 0) {//手机rtmp 播放URL
                            $video['rtmp_sj_url'] = $vv['url'];
                        }
                        if (!strpos($vv['url'], '.flv') && !strpos($vv['url'], '.mp4') && !strpos($vv['url'], '.m3u8') && $vv['definition'] == 0) {//标清rtmp 播放URL
                            $video['rtmp_sd_url'] = $vv['url'];
                        }
                        if (!strpos($vv['url'], '.flv') && !strpos($vv['url'], '.mp4') && !strpos($vv['url'], '.m3u8') && $vv['definition'] == 0) {//高清rtmp 播放URL
                            $video['rtmp_hd_url'] = $vv['url'];
                        }
                    }
                }
                $this->assign("poster", $vodset[0]['fileSet'][sizeof($vodset[0]['fileSet']) - 1]['image_url']);
            } else {
                $this->assign("error", $root['error']);
            }
        } else {
            //直播
            $video['mp4_url'] = $video['play_mp4'];
            $video['m3u8_url'] = $video['play_hls'];
            $video['flv_url'] = $video['play_flv'];
            $video['rtmp_url'] = $video['play_rtmp'];
            if ($video['play_url']) {
                $video['mp4_url'] = get_spec_image($video['play_url']);
            }
        }
        $guessinglog_list = M('guessing_log')->where(array('room_id' => $video_id))->order('id desc')->select(); // 开奖历史记录
        $guessing_list = M('Guessing')->where(array('xiacai_id' => $xiacai_id))->select(); // 竞猜列表
        $guessing_status = intval(M('guessing_log')->where(array('room_id' => $video_id))->order('id desc')->getField('status')); // 竞猜状态
        $guessing_status_text = '';
        if ($guessing_status) {
            if ($guessing_status == 1) {
                $guessing_status_text = '进行中';
            } else if ($guessing_status == 2) {
                $guessing_status_text = '已开奖';
            } else if ($guessing_status == 3) {
                $guessing_status_text = '已停止';
            }
        } else {
            $guessing_status_text = '-';
        }
        if (!isset($video['push_rtmp'])) {
            $video['push_rtmp'] = '';
        }
        $xiacai = M('Xiacai')->find($xiacai_id);
        $this->assign("xiacai", $xiacai);
        $this->assign('guessinglist', $guessing_list);
        $this->assign('guessingloglist', $guessinglog_list);
        $this->assign('guessing_status', $guessing_status_text);
        $this->assign("video", $video);
        $this->display();
    }

    public function error_reset() {
        $xiacai_id = intval($_REQUEST['xiacai_id']);
        $room_id = intval($_REQUEST['room_id']);
        M('Xiacai')->where(array('id' => $xiacai_id))->setField('room_id', 0);
        $this->assign("jumpUrl", '/m.php?m=Xiacai&a=index');
        $this->success('操作成功', $ajax);
    }

}

?>